//
//  LoginViewController.m
//  Audit
//
//  Created by fenggu07 on 15/2/5.
//  Copyright (c) 2015年 cc. All rights reserved.
//

#import "LoginViewController.h"
//#import "PIViewController.h"
#import "FlashViewController.h"
#import "LanguageChooseViewController.h"
#import "AppDelegate.h"


@interface LoginViewController ()
{
    IBOutlet UITextField *_userNameTextField;
    IBOutlet UITextField *_passwordTextField;
    IBOutlet UIButton    *_loginBtn;
}
@property(nonatomic,retain) FlashViewController *flashVC;
@property(nonatomic,retain) LanguageChooseViewController *languageVC;
@end

@implementation LoginViewController 

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [_userNameTextField addTarget:self action:@selector(checkInput:) forControlEvents:UIControlEventEditingChanged];
    
    _userNameTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
    
    _userNameTextField.delegate = (id<UITextFieldDelegate>)self;
    _passwordTextField.delegate = (id<UITextFieldDelegate>)self;
    
    _userNameTextField.returnKeyType = UIReturnKeyNext;
    _passwordTextField.returnKeyType = UIReturnKeyNext;
    
    _userNameTextField.tag = 1001;
    _passwordTextField.tag = 1002;
    _loginBtn.tag          = 1003;
    
    
    //使用NSNotificationCenter 鍵盤出現時
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWasShown:)
     
                                                 name:UIKeyboardDidShowNotification object:nil];
    
    //使用NSNotificationCenter 鍵盤隐藏時
    [[NSNotificationCenter defaultCenter] addObserver:self
     
                                             selector:@selector(keyboardWillBeHidden:)
     
                                                 name:UIKeyboardWillHideNotification object:nil];
}

- (void)checkInput:(UITextField *)textField
{
    textField.text = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
}

- (void)keyboardWasShown:(NSNotification*)aNotification
{
    [UIView animateWithDuration:.8f animations:^{
        self.view.transform = CGAffineTransformMakeTranslation(0,-260);
    }];
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    [UIView animateWithDuration:.8f animations:^{
        self.view.transform = CGAffineTransformIdentity;
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if(textField.returnKeyType == UIReturnKeyNext){       //显示下一个
        if (textField.tag == 1001) {
            [_passwordTextField becomeFirstResponder];
        }
        if (textField.tag == 1002) {
            [_passwordTextField resignFirstResponder];
            
            [self loginAction:_loginBtn];
        }
        
    }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [textField becomeFirstResponder];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_userNameTextField resignFirstResponder];
    [_passwordTextField resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -旋转
- (BOOL)shouldAutorotate
{
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        return YES;
    }
    return NO;
}

//登录
-(IBAction)loginAction:(id)sender
{
    
    //debug
//    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
//    [delegate showMainView];
//    
//    self.flashVC = [[FlashViewController alloc] init];
//    [self.view addSubview:self.flashVC.view];
//    [self performSelector:@selector(hiddenFlash) withObject:nil afterDelay:3];
//    
//    return ;
    
    
    NSArray *keyArr=[NSArray arrayWithObjects:@"userName",@"passWord", nil];
    NSArray *valueArr=[NSArray arrayWithObjects:_userNameTextField.text,_passwordTextField.text, nil];
//    NSArray *valueArr=[NSArray arrayWithObjects:@"admin",@"Pass1234", nil];
    
    [[NSUserDefaults standardUserDefaults] setObject:_userNameTextField.text forKey:@"userName"];
    
    [gAlert showLoading:nil delegate:nil];
    [CommunicateWithService communicateWithService:keyArr value:valueArr apiName:@"login.do" finishSelector:@selector(loginFinished:) failSelector:@selector(loginFailed:) delegateObj:self];
}

//请求服务器成功
-(void)loginFinished:(ASIHTTPRequest *)request
{
//    [gAlert dismiss];
    if (request.responseStatusCode == 400) {
        //textView.text = @"Invalid code";
        NSLog(@"Invalid code");
    } else if (request.responseStatusCode == 403) {
        NSLog(@"Code already used");
        //textView.text = @"Code already used";
    } else if (request.responseStatusCode == 200) {
        NSDictionary *strDic=[CommunicateWithService getDataDic:request.responseString];//解析json 2 dic
        
        NSString *flag = [strDic objectForKey:@"resultCode"];//服务器返回代码
        
        NSString *msg = [strDic objectForKey:@"resultValue"];//服务器返回提示消息
        
        NSString *strDicData = [strDic objectForKey:@"resultData"];//服务器返回数据字典
        
        if ([flag isEqualToString:@"1001"]) {
            //进入主页面
    
            AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
            [delegate showMainView];
            delegate.userId = strDicData;
            
            self.flashVC = [[FlashViewController alloc] init];
            [self.view addSubview:self.flashVC.view];
            [self performSelector:@selector(hiddenFlash) withObject:nil afterDelay:3];
        }
        else if ([flag isEqualToString:@"1002"])
        {
            [gAlert dismiss];
            [gAlert show:msg inView:self.view delegate:nil];
        }
    }
}

-(void)hiddenFlash
{
    [self.flashVC.view removeFromSuperview];
    
    self.languageVC = [[LanguageChooseViewController alloc] init];
    [self.view addSubview:self.languageVC.view];
}



//请求服务器失败
-(void)loginFailed:(ASIHTTPRequest *)request
{
//    NSLog(@"%d",request.responseStatusCode);
    
    [gAlert dismiss];
    [NetworkCheck checkNetwork:self];//检查网络
}

@end
